/*
 * timer.c
 *
 *  Created on: May 15, 2011
 *      Author: Nicholas Swartzendruber
 */

#include <stdio.h>
#include <pthread.h>
#include "./timer.h"

/**
 * A main function for testing purposes. This is
 * because unit testing is difficult to do with
 * the timer.
 * TODO Delete upon finalization.
 */
int main() {
	timer t =timer_initialize();
	t->ms = 50;
	timer_start(t);
	sleep(2);
	timer_stop(t);
	printf("STOP\n");
	sleep(2);
	printf("2sec after stop\n");
	return;
}

/**
 * Called to allocate memory for a timer.
 * @return A timer pointer that may executed in it's own thread.
 */
timer timer_initialize() {
	timer t = (timer) malloc(sizeof(timer_str));
	t->ms = DEFAULT_MS;
	t->stop = FALSE;
	return t;
}

/**
 * Called to start the passed timer. Timer
 * will be STARTED ON IT'S OWN THREAD.
 * @return void
 */
void timer_start(timer t) {
	pthread_t pth;
	pthread_create(&pth, NULL, timer_thread_start, t);
	return;
}

/**
 * Helper method for starting a time on
 * it's own thread.
 * @return void
 */
void * timer_thread_start(timer t) {
	while(t->stop == FALSE) {
		//TODO Change the print to a function call.
		printf("This is a print from timer, replace with function call.\n");
		usleep(t->ms * 1000);
	}
	t->stop = FALSE;
	return;
}

/**
 * Called to stop the timer that has
 * been passed.
 * @return void
 */
void timer_stop(timer t) {
	t->stop = TRUE;
	return;
}

